package com.example.aisqlmcp.mcp.util;

import com.example.aisqlmcp.mcp.config.MCPApiKeyInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class MCPContextUtil {
    
    /**
     * 从当前请求中获取API密钥
     * @return API密钥，如果不存在则返回null
     */
    public static String getCurrentApiKey() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Object apiKeyObj = request.getAttribute(MCPApiKeyInterceptor.API_KEY_ATTRIBUTE);
            return apiKeyObj != null ? apiKeyObj.toString() : null;
        }
        return null;
    }
    
    /**
     * 从指定请求中获取API密钥
     * @param request HTTP请求
     * @return API密钥，如果不存在则返回null
     */
    public static String getApiKeyFromRequest(HttpServletRequest request) {
        Object apiKeyObj = request.getAttribute(MCPApiKeyInterceptor.API_KEY_ATTRIBUTE);
        return apiKeyObj != null ? apiKeyObj.toString() : null;
    }
}